package com.scorpio.appuser.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.scorpio.appuser.constant.UserRedisConstant;
import com.scorpio.appuser.domain.UserEntity;
import com.scorpio.appuser.dto.FressTotaiDTO;
import com.scorpio.appuser.service.ChatMessageServer;
import com.scorpio.appuser.service.UserServer;
import com.scorpio.appuser.vo.LocationInfoVo;
import com.scorpio.chatnotify.domain.AutoGreetEntity;
import com.scorpio.chatnotify.domain.AutoGreetRecordEntity;
import com.scorpio.chatnotify.service.AutoGreetRecordService;
import com.scorpio.chatnotify.service.IAutoGreetService;
import com.scorpio.common.annotation.DataSource;
import com.scorpio.common.enums.DataSourceType;
import com.scorpio.common.factory.AsyncManager;
import com.scorpio.common.utils.DateUtils;
import com.scorpio.common.utils.MathUtil;
import com.scorpio.common.utils.im.IMTemplate;
import com.scorpio.common.utils.StringUtils;
import com.scorpio.common.utils.http.HttpUtils;
import com.scorpio.common.utils.http.Request;
import com.scorpio.common.utils.im.TLSSigAPIv2;
import com.scorpio.redis.RedisCache;
import com.scorpio.redis.constant.RedisConstants;
import com.scorpio.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

@Service
@DataSource(DataSourceType.SLAVE)
public class ChatMessageServerImpl implements ChatMessageServer {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private UserServer userServer;

    @Autowired
    private IAutoGreetService autoGreetService;

    @Autowired
    private AutoGreetRecordService autoGreetRecordService;

    @Override
    public FressTotaiDTO appendSendMessage(UserEntity entity, Long toUserId) {
        String fressTotai = configService.selectConfigByKey(UserRedisConstant.fressTotai);
        Long maxTotal = StringUtils.isEmpty(fressTotai) ? 0L : Long.valueOf(fressTotai);
        FressTotaiDTO dto = new FressTotaiDTO();
        String key = UserRedisConstant.chatIncrement + DateUtils.getDate() + ":" + entity.getId();
        dto.setTodayTotal(redisCache.increment(key, 1));
        dto.setMaxTotal(maxTotal);
        redisCache.expire(key, 1, TimeUnit.DAYS);
        return dto;
    }

    @Override
    public void massSendMessage(UserEntity entity, LocationInfoVo vo) {
        AsyncManager.me().execute(new TimerTask() {
            @Override
            @Transactional
            public void run() {
                String totaliyValue = configService.selectConfigByKey("massSendMessage");
                int totaliy = 0;
                if (!StringUtils.isEmpty(totaliyValue)) {
                    totaliy = Integer.valueOf(totaliyValue);
                }
                if (totaliy <= 0) return;
                if (!"4".equals(entity.getStatus())) return;
                if (!"2".equals(entity.getSex())) return;
                StringBuilder aotoGerr = new StringBuilder();
                StringBuilder ids = new StringBuilder();
                List<UserEntity> list = userServer.nearestList(entity.getId(), vo.getLng(), vo.getLat(), "1".equals(entity.getSex()) ? 2 : 1, totaliy);
                if (list.size() > 0) {
                    for (UserEntity userEntity : list) {
                        String accounts = "" + userEntity.getId();
                        AutoGreetEntity autoGreetEntity = autoGreetService.selectRrandOne(entity.getSex());
                        if (autoGreetEntity != null) {
                            JSONObject json = IMTemplate.sendMsg(2, "" + entity.getId(), accounts, IMTemplate.messageTextElem(autoGreetEntity.getContent()));
                            if (SendMsg(json)) {
                                logger.info("IM发送成功:" + json.toJSONString());
                                aotoGerr.append(autoGreetEntity.getContent() + ",");
                                ids.append(accounts + ",");
                            }
                        }
                    }
                    AutoGreetRecordEntity recordEntity = new AutoGreetRecordEntity();
                    recordEntity.setContent(aotoGerr.toString());
                    recordEntity.setUserId(entity.getId());
                    recordEntity.setSendTotal(totaliy);
                    recordEntity.setToUserIds(ids.toString());
                    autoGreetRecordService.save(recordEntity);
                }
            }
        });
    }

    public boolean SendMsg(JSONObject body) {
        String timHost = configService.selectConfigByKey("tencent:tim:host");
        String appid = configService.selectConfigByKey("tencent:tim:appid");
        String sendmsg = configService.selectConfigByKey("tencent:tim:sendmsg");
        String identifier = configService.selectConfigByKey("tencent:tim:admin");
        String str = HttpUtils.request(new Request()
                .url(timHost + sendmsg + String.format("?sdkappid=%s&identifier=%s&usersig=%s&random=%s&contenttype=json"
                        , appid
                        , identifier
                        , getUsersig(identifier)
                        , MathUtil.getRandLetter(MathUtil.NUMERIC, 8)))
                .post()
                .body(body)
        );
        JSONObject json = JSONObject.parseObject(str);
        if (json.getInteger("ErrorCode") == 0 && "OK".equals(json.getString("ActionStatus"))) {
            logger.info("打招呼成功");
            return true;
        } else {
            logger.error("打招呼失败:" + json.toJSONString());
            return false;
        }
    }

    /**
     * 群发消息
     *
     * @param body
     */
    public boolean batchSendMsg(JSONObject body) {
        String timHost = configService.selectConfigByKey("tencent:tim:host");
        String appid = configService.selectConfigByKey("tencent:tim:appid");
        String batchsendmsg = configService.selectConfigByKey("tencent:tim:batchsendmsg");
        String identifier = configService.selectConfigByKey("tencent:tim:admin");

        String str = HttpUtils.request(new Request()
                .url(timHost + batchsendmsg + String.format("?sdkappid=%s&identifier=%s&usersig=%s&random=%s&contenttype=json"
                        , appid
                        , identifier
                        , getUsersig(identifier)
                        , MathUtil.getRandLetter(MathUtil.NUMERIC, 8)))
                .post()
                .body(body)
        );
        JSONObject json = JSONObject.parseObject(str);
        if (json.getInteger("ErrorCode") == 0 && "OK".equals(json.getString("ActionStatus"))) {
            logger.info("群发打招呼成功");
            return true;
        } else {
            logger.error("群发打招呼失败:" + json.toJSONString());
            return false;
        }
    }

    private String getUsersig(String identifier) {
        String key = RedisConstants.SYS_CACHE_KEY + "usersig";
        String usersig = redisCache.getCacheObject(key);
        if (usersig == null) {
            int expire = 86400;
            String appid = configService.selectConfigByKey("tencent:tim:appid");
            String secret = configService.selectConfigByKey("tencent:tim:secret");
            TLSSigAPIv2 tlsSigAPIv2 = new TLSSigAPIv2(Long.valueOf(appid), secret);
            usersig = tlsSigAPIv2.genUserSig(identifier, expire);
            redisCache.setCacheObject(key, usersig, expire, TimeUnit.SECONDS);
        }
        return usersig;
    }
}
